<template>
  <!-- 搜索栏 -->
  <el-card class="search-card">
    <el-form :model="searchForm" label-width="80px" inline>
      <el-form-item label="工单编号">
        <el-input v-model="searchForm.productionOrderCode" placeholder="工单编号" clearable/>
      </el-form-item>
      <el-form-item label="工单名称">
        <el-input v-model="searchForm.productionOrderName" placeholder="工单名称" clearable/>
      </el-form-item>
      <el-form-item label="工单来源">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderSource"
                   placeholder="工单来源">
          <el-option label="客户订单" :value="1"/>
          <el-option label="库存备货" :value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="工单类型">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderType"
                   placeholder="工单类型">
          <el-option
              v-for="dictData in productionOrderTypeDictDataList"
              :value="dictData.id"
              :key="dictData.id"
              :label="dictData.dictLabel"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物料编号">
        <el-input v-model="searchForm.materialCode" placeholder="物料编号" clearable/>
      </el-form-item>
      <el-form-item label="客户编号">
        <el-input v-model="searchForm.customerCode" placeholder="客户编号" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 列表 -->
  <el-card class="table-card">
    <el-table :data="productionOrderList" border stripe>
      <el-table-column prop="productionOrderCode" label="工单编号">
        <template #default="scope">w
          <el-link type="primary" @click="handlerShowProcess(scope.row)">{{
              scope.row.productionOrderCode
            }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="productionOrderName" label="工单名称"/>
      <el-table-column prop="productionOrderSource" label="工单来源">
        <template #default="scope">
          {{ scope.row.productionOrderSource == 1 ? '客户订单' : '库存备货' }}
        </template>
      </el-table-column>
      <el-table-column prop="productionOrderType" label="工单类型">
        <template #default="scope">
          {{
            scope.row.productionOrderType == 30 ? '自产' : scope.row.productionOrderType == 31 ? '外协' : '外购'
          }}
        </template>
      </el-table-column>
      <el-table-column prop="orderCode" label="订单编号"/>
      <el-table-column prop="materialCode" label="产品/物料编号"/>
      <el-table-column prop="material.name" label="产品/物料名称"/>
      <el-table-column prop="material.specification" label="规格"/>
      <el-table-column prop="material.unit.name" label="单位"/>
      <el-table-column prop="productionOrderQuantity" label="排产数量"/>
      <el-table-column label="已生产数量">
        {{ 0 }}
      </el-table-column>
      <el-table-column prop="customer.code" label="客户编号"/>
      <el-table-column prop="customer.name" label="客户名称"/>
      <el-table-column prop="requestDate" label="需求日期"/>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          {{
            scope.row.status == 30 ? '草稿' : scope.row.status == 31 ? '已确认' : scope.row.status == 32 ? '已审核' : '已完成'
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleSchdule(scope.row)">排产</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 分页栏 -->
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!-- 工单详情弹窗 -->
  <el-dialog :title="dialogTitle" v-model="addOrUpdateDialogVisable" @close="closeDialog" width="80%">
    <el-form :model="productionOrderForm" label-width="120px">
      <el-form-item label="工单编号">
        <el-input :disabled="isDetail" v-model="productionOrderForm.productionOrderCode"/>

      </el-form-item>
      <el-form-item label="工单名称">
        <el-input :disabled="isDetail" v-model="productionOrderForm.productionOrderName"/>
      </el-form-item>
      <el-form-item label="单据来源">
        <el-select style="width: 120px" clearable :disabled="isDetail"
                   v-model="productionOrderForm.productionOrderSource" placeholder="单据来源">
          <el-option label="客户订单" :value="1"/>
          <el-option label="库存备货" :value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="工单类型">
        <el-select style="width: 120px" clearable :disabled="isDetail"
                   v-model="productionOrderForm.productionOrderType" placeholder="工单类型">
          <el-option
              v-for="dictData in productionOrderTypeDictDataList"
              :value="dictData.id"
              :key="dictData.id"
              :label="dictData.dictLabel"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工单编码">
        <el-input :disabled="isDetail" v-model="productionOrderForm.orderCode"/>
      </el-form-item>
      <el-form-item label="物料编码">
        <el-input :disabled="isDetail" v-model="productionOrderForm.materialCode"/>
      </el-form-item>
      <el-form-item label="排产数量">
        <el-input :disabled="isDetail" v-model="productionOrderForm.productionOrderQuantity"/>
      </el-form-item>
      <el-form-item label="客户编码">
        <el-input :disabled="isDetail" v-model="productionOrderForm.customerCode"/>
      </el-form-item>
      <el-form-item label="需求日期">
        <el-date-picker :disabled="isDetail" v-model="productionOrderForm.requestDate" type="date"
                        placeholder="选择日期"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select style="width: 120px;" :disabled="isDetail" v-model="productionOrderForm.status"
                   placeholder="请选择状态" clearable>
          <el-option
              v-for="dictData in productionOrderStatusDictDataList"
              :label="dictData.dictLabel"
              :value="dictData.id"
              :key="dictData.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :disabled="isDetail" label="二维码URL">
        <el-input v-model="productionOrderForm.qrCodeUrl"/>
      </el-form-item>
    </el-form>
    <!-- 物料工艺列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>工艺流程</span>
        </div>
      </template>
      <el-table
          :data="workflowList"
          border
          stripe
      >
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="workflowCode" label="工艺编号"/>
        <el-table-column prop="workflowName" label="工艺名"/>
        <el-table-column prop="workflowDescription" label="工艺流程说明"/>
        <el-table-column prop="createTime" label="创建时间" width="180"/>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status == '1' ? 'success' : 'danger'">
              {{ scope.row.status == '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleShow(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <!--        <el-button v-if="isEdit && productionOrderForm.status == 30" @click="confirmProductionOrderForm(productionOrderForm)">确定</el-button>-->
        <!--        <el-button v-if="!isEditOrAdd" type="primary" @click="saveProductionOrderForm">提交</el-button>-->
      </span>
    </template>
  </el-dialog>
  <!-- 工序步骤弹窗 -->
  <el-dialog
      :title="workflowProcessDialogTitle"
      v-model="workflowProcessDialogVisible"
      width="80%"
      @close="handleDialogClose"
  >
    <el-row style="margin: 10px">
      <el-col :span="12">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedTask.length === 0">批量删除</el-button>
      </el-col>
    </el-row>
    <el-col :span="24">
      <el-table
          :data="workflowProcessList"
          stripe
          border
          @selection-change="handleSelectionChange"
          style="width: 100%">
        <el-table-column type="selection" width="55"/>
        <el-table-column fixed="left" prop="id" label="ID"/>
        <el-table-column fixed="left" prop="stepOrder" label="序号"/>
        <el-table-column fixed="left" prop="process.processCode" label="工序编号"/>
        <el-table-column fixed="left" prop="process.processName" label="工序名称"/>
        <el-table-column fixed="left" prop="workstationCode" label="工作站编号"/>
        <el-table-column fixed="left" prop="workstationName" label="工作站名称"/>
        <el-table-column fixed="left" prop="proScheduleQuantity" label="排产数量"/>
        <el-table-column fixed="left" prop="proScheduleQuantity" label="已生产数量">
          {{ 0 }}
        </el-table-column>
        <el-table-column prop="nextProcess.processName" label="下一道工序">
          <template v-slot="scope">
            {{ scope.row.nextProcess ? scope.row.nextProcess.processName : '无' }}
          </template>
        </el-table-column>
        <el-table-column prop="relationNextDict.dictLabel" label="与下一道工序关系">
          <template v-slot="scope">
            {{ scope.row.nextProcess ? scope.row.relationNextDict.dictLabel : '无' }}
          </template>
        </el-table-column>
        <el-table-column prop="isCritical" label="关键工序">
          <template v-slot="scope">
            <el-tag :type="scope.row.isCritical == '1' ? 'success' : 'danger'">
              {{ scope.row.isCritical == '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="needInspection" label="质检确认">
          <template v-slot="scope">
            <el-tag :type="scope.row.needInspection == '1' ? 'success' : 'danger'">
              {{ scope.row.needInspection == '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="prepTime" label="准备时间(min)"/>
        <el-table-column prop="waitTime" label="等待时间(min)"/>
        <el-table-column prop="ganttColor" label="甘特图颜色">
          <template v-slot="scope">
            <el-color-picker v-model="scope.row.ganttColor" disabled/>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="small" @click="handlerAddWorkflowProcess(scope.row)">新增</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <template #footer>
      <el-button @click="exitProcessSteps">退出</el-button>
    </template>
  </el-dialog>


  <!-- 新增/修改生产任务弹窗 -->
  <el-dialog :title="taskDialogTitle" v-model="addOrUpdateProductdialogVisible">
    <el-form ref="workflowProductFormRef" :model="workflowProductForm"
             @close="closeTaskDialog" label-width="auto">
      <el-row>
        <el-col :span="12">
          <el-form-item label="序号">
            <el-input-number v-model="workflowProductForm.stepOrder"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工序">
            <el-select v-model="workflowProductForm.processId" placeholder="请选择工序">
              <el-option
                  v-for="item in processList"
                  :key="item.id"
                  :label="item.processName"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="与下一道工序关系">
            <el-tooltip
                class="box-item"
                effect="dark"
                placement="right"
            >
              <template #content>
                <template v-for="item in relationNextContent">
                  {{ item }}<br/>
                </template>
              </template>
              <el-select v-model="workflowProductForm.relationNext" placeholder="请选择与下一道工序关系">
                <el-option
                    v-for="item in relationNextList"
                    :key="item.id"
                    :label="item.dictLabel"
                    :value="item.id"
                />
              </el-select>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工作站编号">
              <el-input v-model="workflowProductForm.workstationCode" placeholder="工作站编号">
                <template #append>
                  <el-button @click="showProductList(currentProcessId.value)">
                    <el-icon>
                      <Search/>
                    </el-icon>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="工作站名称">
              <el-input type="textarea" v-model="workflowProductForm.workstationName" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排产数量">
              <el-input-number v-model="workflowProductForm.proScheduleQuantity"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甘特图颜色">
              <el-color-picker v-model="workflowProductForm.ganttColor"/>
            </el-form-item>
          </el-col>
          <el-row>
            <el-col :span="12">
              <el-form-item label="关键工序">
                <el-radio-group v-model="workflowProductForm.isCritical">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质检确认">
                <el-radio-group v-model="workflowProductForm.needInspection">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="准备时间(min)">
                <el-input-number v-model="workflowProductForm.prepTime"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="等待时间(min)">
                <el-input-number v-model="workflowProductForm.waitTime"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" v-model="workflowProductForm.remarks" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="cancelAddOrUpdate">取消</el-button>
      <el-button type="primary" @click="handlerSubmit">保存</el-button>
    </template>
  </el-dialog>
  <!-- 工作站列表弹窗 -->
  <el-dialog
      title="选择工作站"
      v-model="productListDialogVisable"
      width="80%"
      @close="handleWorkstationDialogClose"
  >
    <el-row style="margin:15px">
      <el-form inline v-model="searchWorkstationForm">
        <el-form-item label="工作站编号">
          <el-input v-model="searchWorkstationForm.code" placeholder="工作站编号"/>
        </el-form-item>
        <el-form-item label="工作站名称">
          <el-input v-model="searchWorkstationForm.name" placeholder="工作站名称"/>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="loadWorkstationList" >搜索</el-button>
          <el-button @click="resetSearchWorkstation">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row style="margin:15px">
      <el-radio-group v-model="selectedWorkstationCode" style="width: 100%">
        <el-table
            :data="workstationList"
            stripe
            border
            width="100%"
        >
          <el-table-column>
            <template #default="scope">
              <!-- 绑定工作站编码 -->
              <el-radio :value="scope.row.code"/>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="工作站编码"/>
          <el-table-column prop="name" label="工作站名称"/>
          <el-table-column prop="workshopId" label="所属车间编号"/>
          <el-table-column prop="location" label="工作站地点"/>
          <el-table-column prop="processId" label="所属工序编号"/>
          <el-table-column prop="description" label="工作站描述"/>
        </el-table>
      </el-radio-group>
    </el-row>
    <el-row>
      <el-button @click="doSelectWorkstation">确定</el-button>
    </el-row>
  </el-dialog>
  <!--    <el-dialog v-model="productListDialogVisable" title="选择工作站" width="80%">-->
  <!--        &lt;!&ndash; 绑定 process-id，将当前工序ID传递给子组件 &ndash;&gt;-->
  <!--        <WorkstationList :process-id="currentProcessId.value" @select-workstation="handlerSelectWorkstation"/>-->
  <!--    </el-dialog>-->
</template>

<script setup>
import {ref, onMounted} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {getDictDataList} from "@/api/dictData.js";
import {
  getProductionOrderListStatus,
  queryById,
  selectWorkflowById
} from "@/api/production-order.js";
import {
  batchDeleteWorkflowProcess, deleteWorkflowProcess,
  getWorkflowProcessById,
  getWorkflowProcessPage, insertProTask, updateProTaskById
} from "@/api/workflowProcess.js";
import {getProcessList} from "@/api/process.js";
import {selectByCodeOrName, selectByProcessId, selectWorkstationByCode} from "@/api/workstation.js";

const relationNextContent = ref([])
const relationNextList = ref([])
const processList = ref([])
//搜索工作站表单
const searchWorkstationForm = ref({
  code:'',
  name:''
});
//搜索工单表单
const searchForm = ref({
  productionOrderCode: "",
  productionOrderName: "",
  materialCode: "",
  status: "",
  productionOrderSource: "",
  customerCode: "",
  productionOrderType: ""
})
//生产任务表单
const workflowProductForm = ref({
  id: '',
  workflowId: '',
  processId: '',
  stepOrder: '',
  relationNext: '',
  workstationCode: '',
  proScheduleQuantity: '',
  workstationName: '',
  ganttColor: '',
  isCritical: '',
  needInspection: '',
  prepTime: '',
  waitTime: '',
  remarks: '',
  isProcessDisabled: false,//判断新增和编辑
});
//工艺分页对象
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});
//工单类型字典
const productionOrderTypeDictDataList = ref([])
// 工单状态字典列表
const productionOrderStatusDictDataList = ref([]);
//工单列表
const productionOrderList = ref([])
//弹窗标题
const dialogTitle = ref("");
//弹窗显示标记
const addOrUpdateDialogVisable = ref(false);
//新增/编辑表单数据
const productionOrderForm = ref({});
//是否显示详情
const isDetail = ref(false);
//物料工艺列表数据
const workflowList = ref([])
//工序步骤弹窗标题
const workflowProcessDialogTitle = ref('')
//工序步骤弹窗显示标记
const workflowProcessDialogVisible = ref(false)
//工序步骤列表
const workflowProcessList = ref([])
//展示工序步骤列表
const isShowWorkflowProcess = ref(false)
//工序步骤page和size的响应式对象
// const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
//生产任务弹窗标题
const taskDialogTitle = ref('')
//生产任务弹窗显示标记
const addOrUpdateProductdialogVisible = ref(false)
//工作站弹窗标记
const productListDialogVisable = ref(false)
//父组件中定义当前工序ID
const processId = ref(null);
//工作站列表
const workstationList = ref([]);
const total = ref(0)
const page = ref(1)
const size = ref(10)
//保存点击新增时的工序ID
const currentProcessId = ref(null);
//保存点击新增时的工艺ID
const currentWorkflowId = ref(null);
//选择工作站
const selectedWorkstationCode = ref('');
//编辑工序步骤弹窗标记
const isEdit = ref(false);
// 选中的生产任务
const selectedTask = ref([])
//重置工作站搜索栏
const resetSearchWorkstation = () => {
  searchWorkstationForm.value.code = "";
  searchWorkstationForm.value.name = "";
}
//多条件搜索工作站
const loadWorkstationList = () => {
  const queryParams = {
    processId: currentProcessId.value, //当前工序ID
    code:searchWorkstationForm.value.code,
    name:searchWorkstationForm.value.name,
  };
  selectByCodeOrName(1,10000,queryParams).then(res=>{
    workstationList.value = res.data.list;
  })
}
// 处理选中项变化
const handleSelectionChange = (selection) => {
  selectedTask.value = selection
}
//批量删除生产任务
const handleBatchDelete = () => {
  ElMessageBox.confirm(
      `确定要删除选中的 ${selectedTask.value.length} 个用户吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    let params = "";
    selectedTask.value.forEach(item => {
      params += "id=" + item.id + "&"
    })
    params = params.substring(0, params.length - 1)
    batchDeleteWorkflowProcess(params).then(res => {
      ElMessage.success('删除成功')
      loadWorkflowProcessList(processId.value);
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
};

//删除生产任务
const handleDelete=(row)=>{
  ElMessageBox.confirm(
      `确定要删除 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    deleteWorkflowProcess(row.id).then(res => {
      ElMessage.success('删除成功')
      loadWorkflowProcessList(processId.value);
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}
//新增和修改生产任务
const handlerSubmit = () => {
  // 深拷贝响应式表单，生成无循环引用的纯数据对象
  workflowProductForm.value.workflowId = currentWorkflowId.value;
  workflowProductForm.value.processId = currentProcessId.value;
  const workflowProductFormData = JSON.parse(JSON.stringify(workflowProductForm.value));
  if (isEdit.value) {
    updateProTaskById(workflowProductFormData)
        .then(res => {
          if (res.code == 200){
            ElMessage.success("修改流程成功");
            cancelAddOrUpdate();
            if (currentProcessId.value) {
              loadWorkflowProcessList(currentProcessId.value);
            }
          }else{
            ElMessage.error(res.msg);
          }
        })
  } else {
    insertProTask(workflowProductFormData)
        .then(res => {
          if (res.code == 200){
            ElMessage.success("修改流程成功");
            cancelAddOrUpdate();
            if (currentProcessId.value) {
              loadWorkflowProcessList(currentProcessId.value);
            }
          }else{
            ElMessage.error(res.msg);
          }
        })
  }
}
//工作站列表弹窗关闭时，重置选中的工作站编码
const handleWorkstationDialogClose = () => {
  selectedWorkstationCode.value = '';
};
//取消添加生产任务
const cancelAddOrUpdate = () => {
  addOrUpdateProductdialogVisible.value = false;
  closeTaskDialog();
}
//关闭生产任务弹窗
const closeTaskDialog = () => {
  addOrUpdateProductdialogVisible.value = false;
  workflowProductForm.value = {
    id: '',
    workflowId:'',
    processId: '',
    stepOrder: '',
    relationNext: '',
    workstationCode: '',
    proScheduleQuantity: '',
    workstationName: '',
    ganttColor: '',
    isCritical: '',
    needInspection: '',
    prepTime: '',
    waitTime: '',
    remarks: '',
    isProcessDisabled: true,
  };
}
//选择工作站
const doSelectWorkstation = (workstationCode) => {
  if (!workstationCode) {
    ElMessage.warning("请先选择工作站");
    return;
  }
  selectWorkstationByCode(selectedWorkstationCode.value).then(res => {
    const workstation = res.data
    //将工作站 编号 名称 赋值给生产任务表单
    workflowProductForm.value.workstation = workstation;
    workflowProductForm.value.workstationCode = workstation.code;
    workflowProductForm.value.workstationName = workstation.name;
    productListDialogVisable.value = false;
  }).catch(err => {
    ElMessage.error("获取工作站信息失败");
    console.error(err);
  });
}
const getWorkstationList = (processId) => {
  selectByProcessId(1, 10000, {processId: processId}).then(res => {
    workstationList.value = res.data.list
  }).catch(err => {
    ElMessage.error("加载工作站列表失败");
    console.error(err);
  });
}
//展示工作站列表
const showProductList = (processId) => {
  productListDialogVisable.value = true;
  //保存当前工序ID
  currentProcessId.value = processId.value;
  getWorkstationList(processId.value);
}
//查询所有工作站
//添加生产任务弹窗
const handlerAddWorkflowProcess = (row) => {
  isEdit.value = false;
  taskDialogTitle.value = '添加生产任务'
  addOrUpdateProductdialogVisible.value = true;
  currentProcessId.value = row.id;
  currentWorkflowId.value = row.workflowId;
  workflowProductForm.value = {
    id: '',
    workflowId: '',
    processId: '',
    stepOrder: '',
    relationNext: '',
    workstationCode: '',
    proScheduleQuantity: 0,
    workstationName: '',
    ganttColor: '',
    isCritical: 0,
    needInspection: 0,
    prepTime: 0,
    waitTime: 0,
    remarks: '',
    isProcessDisabled: true,
  };
  getWorkstationList(currentProcessId.value);
  getDictDataList({dictType: 'process_next_relation', pageNum: 1, pageSize: 1000})
      .then(res=>{
        relationNextList.value = res.data.records;
        relationNextContent.value = [];
        res.data.records.forEach(item=>{
          relationNextContent.value.push(item.dictLabel + ':' + item.remark)
        })
      })
  getProcessList({pageNum: 1, pageSize: 1000})
      .then(res=>{
        processList.value = res.data.list;
      })
}
//编辑生产任务弹窗
const handleEdit = (row) => {
  isEdit.value = true;
  taskDialogTitle.value = '编辑生产任务'
  currentProcessId.value = row.id;
  addOrUpdateProductdialogVisible.value = true;
  getWorkstationList(currentProcessId.value);
  //编辑弹窗关闭清空数据
  workflowProductForm.value = {
    ...row,
    isProcessDisabled: false,
  };
  getWorkflowProcessById(row.id).then(res => {
    if (res.code === 200) {
      workflowProductForm.value = {
        ...res.data,
        isProcessDisabled: false
      }
    }
  })
  getDictDataList({dictType: 'process_next_relation', pageNum: 1, pageSize: 1000})
      .then(res=>{
        relationNextList.value = res.data.records;
        relationNextContent.value = [];
        res.data.records.forEach(item=>{
          relationNextContent.value.push(item.dictLabel + ':' + item.remark)
        })
      })
  getProcessList({pageNum: 1, pageSize: 1000})
      .then(res=>{
        processList.value = res.data.list;
      })
}
//退出工序步骤
const exitProcessSteps = () => {
  workflowProcessDialogVisible.value = false;
}
//工序步骤弹窗关闭
const handleDialogClose = () => {

}
//加载工序步骤列表
const loadWorkflowProcessList = (workflowId) => {
  getWorkflowProcessPage(page.value, size.value, { workflowId })
      .then(res => {
        workflowProcessList.value = res.data.list;
        total.value = res.data.total;
      })
      .catch(err => {
        ElMessage.error("加载工序步骤列表失败");
        console.error(err);
      });
};
// 查看按钮和加载工序步骤列表
const handleShow = (row) => {
  workflowProcessDialogTitle.value = '工序步骤'
  isShowWorkflowProcess.value = true
  processId.value = row.id; //将当前工艺ID赋值给processId
  workflowProcessDialogVisible.value = true
  loadWorkflowProcessList(row.id);
}
//排产按钮
const handleSchdule = (row) => {
  dialogTitle.value = '详情'
  queryById(row.id).then((res) => {
    productionOrderForm.value = res.data;
    addOrUpdateDialogVisable.value = true;
    LoadWorkflowList(row);
  });
}
//取消按钮
const cancel = () => {
  addOrUpdateDialogVisable.value = false;
  closeDialog();
}
//加载工单物料工艺流程
const LoadWorkflowList = (row) => {
  selectWorkflowById(row.id).then((res) => {
    workflowList.value = res.data;
  });
}
//清空数据 关闭弹窗
const closeDialog = () => {
  productionOrderForm.value = {};
  isDetail.value = false;
}

//查看工单和物料工艺
const handlerShowProcess = (row) => {
  dialogTitle.value = '查看工单的物料工艺流程'
  isDetail.value = true;
  queryById(row.id).then((res) => {
    productionOrderForm.value = res.data;
    addOrUpdateDialogVisable.value = true;
    LoadWorkflowList(row);
  });
}
//工艺页面条数变化
const handleSizeChange = (newSize) => {
  pagination.value.pageSize = newSize;
  handleSearch();
};
//工艺页面页数变化
const handleCurrentChange = (newPage) => {
  pagination.value.currentPage = newPage;
  handleSearch();
};
//加载工单类型字典
const loadProductOrderDictDataList = () => {
  getDictDataList({dictType: "PRODUCTION_ORDER_TYPE"}).then((res) => {
    productionOrderTypeDictDataList.value = res.data.records;
  });
};
// 加载工单状态字典
const loadProductionOrderStatusDictDataList = () => {
  getDictDataList({dictType: "PRODUCTION_ORDER_STATUS"}).then((res) => {
    productionOrderStatusDictDataList.value = res.data.records;
  });
};
//搜索
const handleSearch = () => {
  getProductionOrderListStatus(
      pagination.value.currentPage,
      pagination.value.pageSize,
      searchForm.value
  ).then((res) => {
    productionOrderList.value = res.data.list;
    pagination.value.total = res.data.total;
  });
};
//重置
const resetSearch = () => {
  searchForm.value.productionOrderCode = "";
  searchForm.value.productionOrderName = "";
  searchForm.value.status = "";
  searchForm.value.materialCode = "";
  searchForm.value.customerCode = "";
  searchForm.value.productionOrderSource = "";
  searchForm.value.productionOrderType = "";
};
//钩子函数
onMounted(() => {
  loadProductOrderDictDataList();
  loadProductionOrderStatusDictDataList();
  handleSearch();
});
</script>
<style scoped>
.customer-container {
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>